package lesson13;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class Test05 {
    private String url = "jdbc:mysql://localhost:3306/j183?" +
            "userSSL=true&useUnicode=true&" +
            "characterEncoding=UTF8&serverTimezone=GMT";
    private Connection con = null;
    private PreparedStatement statement = null;
    private ResultSet rs = null;
    public Connection getConnection(){
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            return DriverManager.getConnection(url,"root","lovo");
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    public void close(){
        if(con != null){
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(statement != null){
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    public int add(){
        try{
            con = getConnection();
//            statement = con.createStatement();
            int i = statement.executeUpdate("insert into student(name,gender) values('小二','男')");
            return i;
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            close();
        }
        return 0;

    }
    public List<Student> find(String id){
        List list = new ArrayList();
        try{
            con = getConnection();
//            statement = con.createStatement();
            statement = con.prepareStatement("select * from student where id=?");
            statement.setObject(1,1);

            rs = statement.executeQuery();

            while(rs.next()){
                Student student = new Student();
                student.setName(rs.getString("name"));
                student.setGender(rs.getString("gender"));
                list.add(student);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            close();
        }
        return list;
    }

    public static void main(String[] args) {
        Test05 test05 = new Test05();
//        test05.add();
        System.out.println(test05.find("1"));
    }
}
